package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.srb.oss.config.OssProperties;
import com.atguigu.srb.oss.service.OssService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadImage(MultipartFile multipartFile, String module) {
        // https://桶名.节点名/fileName
        String url;
        String fileName;
        String originalFilename = multipartFile.getOriginalFilename();//aaaabbbb.jpg,UUID.jpg
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String uuid = UUID.randomUUID().toString();
        String path = module + new DateTime().toString("/yyyy/MM/dd/");
        fileName = path + uuid + "." + filenameExtension;

        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT,
                OssProperties.KEY_ID,OssProperties.KEY_SECRET);



        try {
            ossClient.putObject(OssProperties.BUCKET_NAME,fileName,multipartFile.getInputStream(),null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ossClient.shutdown();
        url = "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/"+fileName;
        return url;

    }

    @Override
    public void removeFile(String url) {

        String deletePrefix = "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/";
        String deleteFileName = url.substring(deletePrefix.length());
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT,OssProperties.KEY_ID,OssProperties.KEY_SECRET);
        ossClient.deleteObject(OssProperties.BUCKET_NAME,deleteFileName);
        ossClient.shutdown();
    }
}
